package com.zixi.ai.common.enums;

import com.zixi.ai.common.exception.ServiceException;
import lombok.Getter;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 通用服务状态码
 *
 * <pre>
 * 状态码范围：
 * 12000 ~ 12999
 * </pre>
 *
 * @author wfg
 * @since 1.0, 2019-12-15
 */
@Getter
public enum BizCode {
    // 错误信息
    SUCCESS(12000, "操作成功"),
    ERROR(12001, "操作失败"),
    TEMPLATE_NOT_EXISTS(12002, "模板[%s]不存在"),
    ;

    private final int code;
    private final String msg;

    BizCode(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public ServiceException exception(String msg) {
        return new ServiceException(msg == null ? this.msg : msg, this.code);
    }

    public ServiceException exception() {
        return new ServiceException(this.msg, this.code);
    }

    public ServiceException exceptionFormat(Object... args) {
        return new ServiceException(String.format(this.msg, args), this.code);
    }

    private static final Map<Integer, BizCode> ENUM_MAP = new HashMap<>();

    static {
        ENUM_MAP.putAll(Stream.of(BizCode.values()).collect(Collectors.toMap(BizCode::getCode, e -> e)));
    }

    public static String getMsg(int code) {
        return Optional.of(ENUM_MAP.get(code)).map(BizCode::getMsg).orElse("");
    }
}
